<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="header-left" @tap="goBack">
        <image class="back-icon" src="/static/icons8-返回-50.png" mode="aspectFit"></image>
      </view>
      <text class="header-title">添加设备</text>
      <view class="header-right"></view>
    </view>

    <!-- 添加设备表单 -->
    <view class="form-container">
      <view class="form-group">
        <view class="form-item">
          <text class="label">设备名称</text>
          <input 
            class="input" 
            v-model="deviceInfo.name" 
            placeholder="请输入设备名称"
          />
        </view>
        
        <view class="form-item">
          <text class="label">设备类型</text>
          <picker 
            mode="selector" 
            :range="deviceTypes" 
            range-key="name"
            @change="onTypeChange"
          >
            <view class="picker">
              <text>{{ deviceInfo.type ? getDeviceTypeName(deviceInfo.type) : '请选择设备类型' }}</text>
              <image class="arrow-icon" src="/static/devices/跳转.png" mode="aspectFit"></image>
            </view>
          </picker>
        </view>
        
        <view class="form-item">
          <text class="label">设备位置</text>
          <picker 
            mode="selector" 
            :range="locations" 
            @change="onLocationChange"
          >
            <view class="picker">
              <text>{{ deviceInfo.location || '请选择设备位置' }}</text>
              <image class="arrow-icon" src="/static/devices/跳转.png" mode="aspectFit"></image>
            </view>
          </picker>
        </view>
      </view>
    </view>

    <!-- 保存按钮 -->
    <view class="save-btn" @tap="saveDevice">
      <text>添加设备</text>
    </view>
  </view>
</template>

<script setup lang="ts">
/// <reference types="@dcloudio/types" />
import { ref, reactive } from 'vue';

// 设备信息
const deviceInfo = reactive({
  name: '',
  type: '',
  location: ''
});

// 设备类型列表
const deviceTypes = [
  { id: 'sensor', name: '传感器' },
  { id: 'camera', name: '摄像头' },
  { id: 'controller', name: '控制器' },
  { id: 'irrigation', name: '灌溉' },
  { id: 'light', name: '照明' }
];

// 位置列表
const locations = [
  '1号大棚',
  '2号大棚',
  '3号大棚',
  '仓库',
  '办公室'
];

// 获取设备类型名称
const getDeviceTypeName = (type) => {
  const deviceType = deviceTypes.find(item => item.id === type);
  return deviceType ? deviceType.name : '未知类型';
};

// 选择设备类型
const onTypeChange = (e) => {
  const index = e.detail.value;
  deviceInfo.type = deviceTypes[index].id;
};

// 选择位置
const onLocationChange = (e) => {
  const index = e.detail.value;
  deviceInfo.location = locations[index];
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 保存设备
const saveDevice = async () => {
  // 表单验证
  if (!deviceInfo.name.trim()) {
    uni.showToast({
      title: '请输入设备名称',
      icon: 'none'
    });
    return;
  }
  
  if (!deviceInfo.type) {
    uni.showToast({
      title: '请选择设备类型',
      icon: 'none'
    });
    return;
  }
  
  if (!deviceInfo.location) {
    uni.showToast({
      title: '请选择设备位置',
      icon: 'none'
    });
    return;
  }
  
  // 显示加载提示
  uni.showLoading({
    title: '添加中...'
  });
  
  try {
    // 调用云函数添加设备
    const { result } = await uniCloud.callFunction({
      name: 'addDevice',
      data: {
        deviceInfo: {
          de_name: deviceInfo.name.trim(),
          de_model: deviceInfo.type,
          de_location: deviceInfo.location,
          de_status: 0, // 初始状态为离线
          de_data: {}, // 初始数据为空
          de_lastUpdate: new Date().toISOString(),
          update_time: Date.now()
        }
      }
    });
    
    if (result.code === 0) {
      uni.showToast({
        title: '设备添加成功',
        icon: 'success'
      });
      
      // 延迟返回上一页
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    } else {
      throw new Error(result.message || '添加失败');
    }
  } catch (error) {
    console.error('添加设备失败:', error);
    uni.showToast({
      title: error.message || '添加设备失败',
      icon: 'none'
    });
  } finally {
    uni.hideLoading();
  }
};
</script>

<style>
/* 全局样式 */
page {
  background-color: #f5f7fa;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, sans-serif;
}

.container {
  min-height: 100vh;
  padding-bottom: 120px;
}

/* 顶部导航栏 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background-color: #4CAF50;
}

.header-left {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  width: 24px;
  height: 24px;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
  color: #ffffff;
}

.header-right {
  width: 40px;
}

/* 表单容器 */
.form-container {
  background-color: #ffffff;
  margin-top: 10px;
}

.form-group {
  padding: 0 15px;
}

.form-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.form-item:last-child {
  border-bottom: none;
}

.label {
  font-size: 14px;
  color: #666666;
}

.input {
  flex: 1;
  text-align: right;
  font-size: 14px;
  color: #333333;
  padding: 0 10px;
}

.picker {
  flex: 1;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.picker text {
  font-size: 14px;
  color: #333333;
  margin-right: 10px;
}

.arrow-icon {
  width: 16px;
  height: 16px;
}

/* 保存按钮 */
.save-btn {
  position: fixed;
  left: 15px;
  right: 15px;
  bottom: 30px;
  height: 44px;
  background-color: #4CAF50;
  border-radius: 22px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.save-btn text {
  font-size: 16px;
  color: #ffffff;
}
</style>